package com.bt.lms.ui.action.school_education.transferin_info;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.StuStatusBizTypeConstant;
import com.bt.lms.entity.TransferInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.vo.school_education.transactionInfo.EditTransactionInfoVo;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * 编辑学籍异动验证事件
 */
public class EditTransferInfoVerify implements EventHandler {

    private VBox vBox;

    public EditTransferInfoVerify(VBox box) {
        this.vBox = box;
    }

    @Override
    public void handle(Event event) {


        //1.获取用户输入
        EditTransactionInfoVo editTransactionInfoVo = getInput();
        //2.验证用户输入是否合法
        String verifyMsg = getVerifyMsg(editTransactionInfoVo);
        //3.组包
        byte[] bytes = null;
        if (verifyMsg == null) {
            bytes = handle2Msg(editTransactionInfoVo);
        }
        //4.组网
        Socket socket = getNet();
        //5.发送消息
        boolean flag = sendMsg(bytes, socket, editTransactionInfoVo);

    }

    /**
     * 发送消息
     *
     * @param bytes              字节数组
     * @param socket             网
     * @param editTransactionInfoVo vo对象
     * @return 是否成功
     */
    private boolean sendMsg(byte[] bytes, Socket socket, EditTransactionInfoVo editTransactionInfoVo) {
        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


            //接收响应消息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf);
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();
            if (data != null) {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setContentText("保存成功");
                alert.showAndWait();
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    /**
     * 获取网
     *
     * @return 网
     */
    private Socket getNet() {
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 8888);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return socket;
    }

    /**
     * 根据网络协议组包
     *
     * @param editTransactionInfoVo vo对象
     * @return byte数组
     */
    private byte[] handle2Msg(EditTransactionInfoVo editTransactionInfoVo) {
        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType(StuStatusBizTypeConstant.TRANSACTION_INFO_BIZ_TYPE_ADD);
        reqMsg.setReqId(new Date().getTime());
        TransferInfo transferInfo = new TransferInfo();
        try {
            BeanUtils.copyProperties(transferInfo, editTransactionInfoVo);
            transferInfo.setId(1L);

        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        String transferStr = JSON.toJSONString(transferInfo);
        reqMsg.setData(transferStr);

        return reqMsg.toBytes();

    }

    /**
     * 验证用户输入
     *
     * @param editTransactionInfoVo vo对象
     * @return 验证的消息
     */
    private String getVerifyMsg(EditTransactionInfoVo editTransactionInfoVo) {

        String msg = "";

        if (editTransactionInfoVo.getType() != null) {

        }
        if (editTransactionInfoVo.getBeforeState() != null) {

        }
        if (editTransactionInfoVo.getCause() != null) {
            if (editTransactionInfoVo.getCause().length() > 128) {
                msg += "异动原因在0-128之间\r\n";
            }
        }
        if (editTransactionInfoVo.getLaterState() != null) {

        }
        if (editTransactionInfoVo.getDate() != null) {
            long data = editTransactionInfoVo.getDate().getTime();
            long now = LocalDate.now().atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            if (data > now) {
                msg += "异动日期必须在当前时间之前\r\n";
            }
        }
        if (editTransactionInfoVo.getExplain() != null) {
            if (editTransactionInfoVo.getExplain().length() > 255) {
                msg += "异动说明在0-255位之间\r\n";
            }
        }

        if (!msg.equals("")) {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setContentText(msg);
            alert.show();
        }
        if (msg.equals("")) {
            msg = null;
        }

        return msg;

    }

    /**
     * 获取用户输入
     *
     * @return vo对象
     */
    private EditTransactionInfoVo getInput() {

        EditTransactionInfoVo editTransactionInfoVo = new EditTransactionInfoVo();

        ComboBox anomalousClassCB = (ComboBox) this.vBox.lookup("#anomalousClassCB");
        if (anomalousClassCB.getValue() != null) {
            String anomalousClassStr = (String) anomalousClassCB.getValue();
            int leave = -1;
            switch (anomalousClassStr) {
                case "停学":
                    leave = BOConstant.TRANSFER_INFO_TRANSFER_TYPE_STOP_GOING_TO_SCHOOL;
                    break;
                case "休学":
                    leave = BOConstant.TRANSFER_INFO_TRANSFER_TYPE_QUIT_SCHOOL;
                    break;
                case "停复":
                    leave = BOConstant.TRANSFER_INFO_TRANSFER_TYPE_STOP_AND_RESUME;
                    break;
                case "休复":
                    leave = BOConstant.TRANSFER_INFO_TRANSFER_TYPE_REFRACTORY_PERIOD;
                    break;
                case "退学":
                    leave = BOConstant.TRANSFER_INFO_TRANSFER_TYPE_DROP_OUT;
                    break;
                case "转专业":
                    leave = BOConstant.TRANSFER_INFO_TRANSFER_TYPE_SWITCH_MAJOR;
                    break;
            }
            editTransactionInfoVo.setType(leave);
        }


        ComboBox oldChangeStatusTF = (ComboBox) this.vBox.lookup("#oldChangeStatusTF");
        if (oldChangeStatusTF.getValue() != null) {
            String value = (String) oldChangeStatusTF.getValue();
            int leave = -1;
            switch (value) {
                case "在籍":
                    leave = BOConstant.TRANSFER_INFO_BEFORE_STATE_ON_THE_REGISTER;
                    break;
                case "未注册":
                    leave = BOConstant.TRANSFER_INFO_BEFORE_STATE_UNREGISTERED;
                    break;
                case "休学":
                    leave = BOConstant.TRANSFER_INFO_BEFORE_STATE_QUIT_SCHOOL;
                    break;
                case "退学":
                    leave = BOConstant.TRANSFER_INFO_BEFORE_STATE_DROP_OUT;
                    break;
                case "开除":
                    leave = BOConstant.TRANSFER_INFO_BEFORE_STATE_EXPEL;
                    break;
                case "毕业":
                    leave = BOConstant.TRANSFER_INFO_BEFORE_STATE_GRADUATE;
                    break;
                case "异动中":
                    leave = BOConstant.TRANSFER_INFO_BEFORE_STATE_ALTERNATION;
                    break;
            }
            editTransactionInfoVo.setBeforeState(leave);
        }

        TextField changeReasonTF = (TextField) this.vBox.lookup("#changeReasonTF");
        String changeReasonTFStr = changeReasonTF.getText().trim();
        editTransactionInfoVo.setCause(changeReasonTFStr);

        ComboBox newChangeStatusCB = (ComboBox) this.vBox.lookup("#newChangeStatusCB");
        if (newChangeStatusCB.getValue() != null) {
            String value = (String) newChangeStatusCB.getValue();
            int leave = -1;
            switch (value) {
                case "在籍":
                    leave = BOConstant.TRANSFER_INFO_LATER_STATE_ON_THE_REGISTER;
                    break;
                case "未注册":
                    leave = BOConstant.TRANSFER_INFO_LATER_STATE_UNREGISTERED;
                    break;
                case "休学":
                    leave = BOConstant.TRANSFER_INFO_LATER_STATE_QUIT_SCHOOL;
                    break;
                case "退学":
                    leave = BOConstant.TRANSFER_INFO_LATER_STATE_DROP_OUT;
                    break;
                case "开除":
                    leave = BOConstant.TRANSFER_INFO_LATER_STATE_EXPEL;
                    break;
                case "毕业":
                    leave = BOConstant.TRANSFER_INFO_LATER_STATE_GRADUATE;
                    break;
                case "异动中":
                    leave = BOConstant.TRANSFER_INFO_LATER_STATE_ALTERNATION;
                    break;
            }
            editTransactionInfoVo.setLaterState(leave);
        }
        DatePicker changeDateDP = (DatePicker) this.vBox.lookup("#changeDateDP");
        if (changeDateDP.getValue() != null) {
            LocalDate value = changeDateDP.getValue();
            Instant instant = value.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
            Date from = Date.from(instant);
            editTransactionInfoVo.setDate(from);
        }


        TextArea explainAR = (TextArea) this.vBox.lookup("#explainAR");
        String explainARStr = explainAR.getText().trim();
        editTransactionInfoVo.setExplain(explainARStr);


        return editTransactionInfoVo;
    }
}

